<script setup lang="ts">
/**
 * 用来上传图片
 * 使用 <x-upload v-model="url"/>
 */
import type {UploadProps, UploadRequestOptions} from 'element-plus'
import {uploadFileApi} from "@/api/common/file";
import {DEFAULT_IMAGE_PATH} from "@/utils/constant";

const props = withDefaults(defineProps<{
  modelValue: string | undefined,
  path?: string, // 文件上传到那个文件夹,默认为''
  size?: number // size为1到10,单位为em(自动)
}>(), {
  size: 4,
  path: ''
})
const emit = defineEmits(['update:modelValue'])

let borderRadius = '1em' //
const theSize = computed(() => {
  const {size} = props
  if (typeof size === 'number') {
    if (props.size < 1 || props.size > 10) {
      borderRadius = 4 / 10 + 0.2 + 'em'
      return '4em'
    } else {
      borderRadius = size / 10 + 0.2 + 'em'
      return size + 'em'
    }
  } else {
    borderRadius = 4 / 10 + 0.2 + 'em'
    return '4em'
  }
})

const baseUrl = DEFAULT_IMAGE_PATH
const url = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})
// 用于上传后显示的
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // image/png
  if (!rawFile.type.startsWith('image/')) {
    ElMessage.error('只能上传图片,而你上传的图片格式为:' + rawFile.type)
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('最大上传2M的图片')
    return false
  }
  return true
}

async function handleUpload(options: UploadRequestOptions): Promise<any> {
  const result = await uploadFileApi(options.file, props.path)
  url.value = result.shortUrl
}
</script>

<template>
  <el-upload
      drag
      :http-request="handleUpload"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
  >
    <el-image
        v-if="imageUrl"
        class="my-image"
        :src="imageUrl"
    />
    <el-image
        v-else-if="modelValue"
        crossorigin
        class="my-image"
        :src="baseUrl + modelValue"
    >
      <template #error>
        <div class="empty-photo">
          <i-ep-plus/>
        </div>
      </template>
    </el-image>
    <div v-else class="empty-photo">
      <i-ep-plus/>
    </div>
  </el-upload>
</template>

<style scoped lang="scss">
.my-image {
  height: v-bind(theSize);
  width: v-bind(theSize);
  border-radius: v-bind(borderRadius);
}

:deep(.el-upload-dragger) {
  padding: 0;
  border-radius: 0;
  border: none;
}

.empty-photo {
  height: v-bind(theSize);
  width: v-bind(theSize);
  display: flex;
  border: 2px dashed #8c939d;
  border-radius: v-bind(borderRadius);
  align-items: center;
  justify-content: center;
  color: #8c939d;
}
</style>